iT邦幫忙

2025 iThome 鐵人賽

DAY 3
0

題目介紹

  • 編號:167
  • 類型:Array, Two Pointers, Binary Search
  • 難度:medium
  • 題目連結:https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/submissions/1773931702/
  • 描述:給定一個已排序的整數陣列numbers(升序排列)和一個目標值 target,找出陣列中兩個數,使它們的和為 target。返回這兩個數的索引值,陣列中的每個輸入只會有唯一解,而且不能使用同一個元素兩次。

解題成功圖片:
https://ithelp.ithome.com.tw/upload/images/20250917/20178840K1uBefAI2n.jpg

notion筆記截圖:
https://ithelp.ithome.com.tw/upload/images/20250917/2017884051w9fFDoQJ.jpg
https://ithelp.ithome.com.tw/upload/images/20250917/20178840giSVKV6qvp.pnghttps://ithelp.ithome.com.tw/upload/images/20250917/20178840x1x4ncdQbA.jpg

為什麼這題適合使用 Two Pointers?
這道題已經擁有的三個條件:
-陣列已排序
-題目保證只有一組解
-陣列中數字都是整數,而且沒有要求回傳索引順序
因此可以利用「雙指針」去縮小搜尋區間,一次過陣列即可完成搜尋,不需要多開一個 HashMap,也不會需要額外記憶體,效能就能最佳化。


上一篇
<Day 2> LeetCode 鐵人挑戰規劃表
系列文
「用 LeetCode 挑戰 30 天,打造扎實的程式邏輯力」- 結合Notion記錄學習筆記3
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言